var express = require('express')
var router = express.Router()
var sql = require('../db/mysql')

var fs = require('fs')
var path = require('path')
var multer = require('multer')
var upload = multer({ dest: path.join(path.dirname(__dirname),"public",'admin','images') })

let json = {
  code: 1,
  msg: '登录成功',
  data: []
}

// 登录请求
router.post('/login', async function (req, res, next) {
  console.log(req.body)
  let {
    username,
    password
  } = req.body;
  let users = await sql(`select * from user where username = '${username}'`)
  console.log(users)
  if (users.length == 0) {  // 用户名不存在
    json.code = 0
    json.msg = '用户名不存在！'
    res.send(json)
  } else {  // 用户名存在时
    if (password == users[0].password) {
      json.code = 1
      json.msg = '登录成功'
      res.send(json)
    } else {
      json.code = 2
      json.msg = '密码错误'
      res.send(json)
    }
  }
})
// 获取主页轮播  表 banner
router.get('/getCarousel',async function(req,res,next){
  //解决跨域问题
  res.set("Access-Control-Allow-Origin","*");
  let banner = await sql('select * from banner')
  json.code = 1
  json.msg='成功'
  json.data=banner
  res.send(json)
})
// 增加主页轮播
router.post('/addCarousel',upload.single('avatar'), function(req,res,next){
  res.set("Access-Control-Allow-Origin","*");
  // console.log(req.file)
  // console.log(req.body);
  const file = req.file
   const filepath = file.path
    // 获取上传成功之后的新文件路径
    const filename = file.destination + '\\' + file.originalname
  
  //重命名，借用fs的rename重命名的方法，第一参数是源文件地址路径，第二个参数是将源文件改名后的地址(和参数一地址相同，只不过名字变了而已，两个参数都是地址)
  fs.rename(filepath, filename,err=>{
    if(!err){
      var src = 'http://120.78.191.105/admin/images/' + file.originalname
    }
    // let {data} = req.body
    sql(`insert into banner values(null,'${src}')`).then(data=>{
      res.redirect('/admin/backstage.html')
    })
  })
})
//修改主页轮播图片
router.post('/editCarousel',upload.single('avatar'),function(req,res,next){
  res.set("Access-Control-Allow-Origin","*");
  console.log(req.body)
  //获取图片的信息
  let file = req.file

  if(file !=undefined){
      const filepath = file.path
      const filename = file.destination+"\\"+ file.originalname
      fs.rename(filepath,filename, err =>{
          if(!err){
                  let src = 'http://120.78.191.105/admin/images/'+ file.originalname
                  let {id} = req.body
                  console.log(id);

                  sql(`UPDATE banner set src = '${src}' where id = ${id}`).then(data=>{
                  res.redirect('/admin/backstage.html')
              })
            }
          })
  }else{
          // res.redirect('/admin/backstage.html')
          console.log(err);
  }
})
//删除主页轮播图片
router.post('/delCarousel',async function(req, res, next) {
  res.set("Access-Control-Allow-Origin","*");
  let {id} = req.body
    id = Number(id)
    let editClassTable = await sql(`delete from banner where id = ${id}`)
    console.log(editClassTable)
    res.redirect('/admin/backstage.html')
});

// 企业新闻 媒体关注 表 news
//获取
router.get('/getEnterpriseNews',async function(req,res,next){
  //解决跨域问题
  res.set("Access-Control-Allow-Origin","*");
  let banner = await sql('select * from news')
  json.code = 1
  json.msg='成功'
  json.data=banner
  res.send(json)
})
//增加
router.post('/addEnterpriseNews',upload.single('avatar'), function(req,res,next){
  res.set("Access-Control-Allow-Origin","*");
  console.log(req.file)
  console.log(req.body);
  const file = req.file
  // const extname = path.extname(file.originalname)
   const filepath = file.path
    // 获取上传成功之后的新文件路径
    const filename = file.destination + '\\' + file.originalname
  
  //重命名，借用fs的rename重命名的方法，第一参数是源文件地址路径，第二个参数是将源文件改名后的地址(和参数一地址相同，只不过名字变了而已，两个参数都是地址)
  fs.rename(filepath, filename,err=>{
    if(!err){
      var src = 'http://120.78.191.105/admin/images/' + file.originalname
    }
    // let {data} = req.body
    sql(`insert into news values(null,'${src}')`).then(data=>{
      res.redirect('/admin/backstage.html')
    })
  })
})
//修改
router.post('/editEnterpriseNews',upload.single('avatar'),function(req,res,next){
  res.set("Access-Control-Allow-Origin","*");
  console.log(req.body)
  //获取图片的信息
  let file = req.file

  if(file !=undefined){
      const filepath = file.path
      const filename = file.destination+"\\"+ file.originalname
      fs.rename(filepath,filename, err =>{
          if(!err){
                  let src = 'http://120.78.191.105/admin/images/'+ file.originalname
                  let {id} = req.body
                  console.log(id);

                  sql(`UPDATE news set src = '${src}' where id = ${id}`).then(data=>{
                  res.redirect('/admin/backstage.html')
              })
            }
          })
  }else{
          // res.redirect('/admin/backstage.html')
          console.log(err);
  }
})
//删除
router.post('/delEnterpriseNews',async function(req, res, next) {
  res.set("Access-Control-Allow-Origin","*");
  let {id} = req.body
    id = Number(id)
    let editClassTable = await sql(`delete from news where id = ${id}`)
    console.log(editClassTable)
    res.redirect('/admin/backstage.html')
});

// 奶粉 酸奶 鲜奶等 表 milk  
// 获取
router.get('/getMilk',async function(req,res,next){
  //解决跨域问题
  res.set("Access-Control-Allow-Origin","*");
  let banner = await sql('select * from milk')
  json.code = 1
  json.msg='成功'
  json.data=banner
  res.send(json)
})
//增加
router.post('/addMilk',upload.single('avatar'), function(req,res,next){
  res.set("Access-Control-Allow-Origin","*");
  console.log(req.file)
  console.log(req.body);
  const file = req.file
  // const extname = path.extname(file.originalname)
   const filepath = file.path
    // 获取上传成功之后的新文件路径
    const filename = file.destination + '\\' + file.originalname
  
  //重命名，借用fs的rename重命名的方法，第一参数是源文件地址路径，第二个参数是将源文件改名后的地址(和参数一地址相同，只不过名字变了而已，两个参数都是地址)
  fs.rename(filepath, filename,err=>{
    if(!err){
      var src = 'http://120.78.191.105/admin/images/' + file.originalname
    }
    // let {data} = req.body
    sql(`insert into milk values(null,'${src}')`).then(data=>{
      res.redirect('/admin/backstage.html')
    })
  })
})
//修改
router.post('/editMilk',upload.single('avatar'),function(req,res,next){
  res.set("Access-Control-Allow-Origin","*");
  console.log(req.body)
  //获取图片的信息
  let file = req.file
  if(file !=undefined){
      const filepath = file.path
      const filename = file.destination+"\\"+ file.originalname
      fs.rename(filepath,filename, err =>{
          if(!err){
                  let src = 'http://120.78.191.105/admin/images/'+ file.originalname
                  let {id} = req.body
                  sql(`UPDATE milk set src = '${src}', where id = ${id}`).then(data=>{
                  res.redirect('/admin/backstage.html')
              })
            }
          })
  }else{
          // res.redirect('/admin/backstage.html')
          console.log(err);
  }
})
//删除
router.post('/delMilk',async function(req, res, next) {
  res.set("Access-Control-Allow-Origin","*");
  let {id} = req.body
    id = Number(id)
    let editClassTable = await sql(`delete from milk where id = ${id}`)
    console.log(editClassTable)
    res.redirect('/admin/backstage.html')
});


// 发展历程  表名 develop
// 获取
router.get('/getHistory',async function(req,res,next){
  //解决跨域问题
  res.set("Access-Control-Allow-Origin","*");
  let banner = await sql('select * from develop')
  json.code = 1
  json.msg='成功'
  json.data=banner
  res.send(json)
})
//增加
router.post('/addHistory',upload.single('avatar'), function(req,res,next){
  res.set("Access-Control-Allow-Origin","*");
  console.log(req.file)
  console.log(req.body);
  const file = req.file
  // const extname = path.extname(file.originalname)
   const filepath = file.path
    // 获取上传成功之后的新文件路径
    const filename = file.destination + '\\' + file.originalname
  
  //重命名，借用fs的rename重命名的方法，第一参数是源文件地址路径，第二个参数是将源文件改名后的地址(和参数一地址相同，只不过名字变了而已，两个参数都是地址)
  fs.rename(filepath, filename,err=>{
    if(!err){
      var src = 'http://120.78.191.105/admin/images/' + file.originalname
    }
    // let {data} = req.body
    sql(`insert into develop values(null,'${src}')`).then(data=>{
      res.redirect('/admin/backstage.html')
    })
  })
})
//修改
router.post('/editHistory',upload.single('avatar'),function(req,res,next){
  res.set("Access-Control-Allow-Origin","*");
  console.log(req.body)
  //获取图片的信息
  let file = req.file
  if(file !=undefined){
      const filepath = file.path
      const filename = file.destination+"\\"+ file.originalname
      fs.rename(filepath,filename, err =>{
          if(!err){
                  let src = 'http://120.78.191.105/admin/images/'+ file.originalname
                  let {id} = req.body
                  sql(`UPDATE develop set src = '${src}', where id = ${id}`).then(data=>{
                  res.redirect('/admin/backstage.html')
              })
            }
          })
  }else{
          // res.redirect('/admin/backstage.html')
          console.log(err);
  }
})
//删除
router.post('/delHistory',async function(req, res, next) {
  res.set("Access-Control-Allow-Origin","*");
  let {id} = req.body
    id = Number(id)
    let editClassTable = await sql(`delete from develop where id = ${id}`)
    console.log(editClassTable)
    res.redirect('/admin/backstage.html')
});


// 企业荣誉 轮播  表名honor
// 获取
router.get('/getHonor',async function(req,res,next){
  //解决跨域问题
  res.set("Access-Control-Allow-Origin","*");
  let banner = await sql('select * from honor')
  json.code = 1
  json.msg='成功'
  json.data=banner
  res.send(json)
})
//增加
router.post('/addHonor',upload.single('avatar'), function(req,res,next){
  res.set("Access-Control-Allow-Origin","*");
  console.log(req.file)
  console.log(req.body);
  const file = req.file
  // const extname = path.extname(file.originalname)
   const filepath = file.path
    // 获取上传成功之后的新文件路径
    const filename = file.destination + '\\' + file.originalname
  
  //重命名，借用fs的rename重命名的方法，第一参数是源文件地址路径，第二个参数是将源文件改名后的地址(和参数一地址相同，只不过名字变了而已，两个参数都是地址)
  fs.rename(filepath, filename,err=>{
    if(!err){
      var src = 'http://120.78.191.105/admin/images/' + file.originalname
    }
    // let {data} = req.body
    sql(`insert into honor values(null,'${src}')`).then(data=>{
      res.redirect('/admin/backstage.html')
    })
  })
})
//修改
router.post('/editHonor',upload.single('avatar'),function(req,res,next){
  res.set("Access-Control-Allow-Origin","*");
  console.log(req.body)
  //获取图片的信息
  let file = req.file
  if(file !=undefined){
      const filepath = file.path
      const filename = file.destination+"\\"+ file.originalname
      fs.rename(filepath,filename, err =>{
          if(!err){
                  let src = 'http://120.78.191.105/admin/images/'+ file.originalname
                  let {id} = req.body
                  sql(`UPDATE honor set src = '${src}', where id = ${id}`).then(data=>{
                  res.redirect('/admin/backstage.html')
              })
            }
          })
  }else{
          // res.redirect('/admin/backstage.html')
          console.log(err);
  }
})
//删除
router.post('/delHonor',async function(req, res, next) {
  res.set("Access-Control-Allow-Origin","*");
  let {id} = req.body
    id = Number(id)
    let editClassTable = await sql(`delete from honor where id = ${id}`)
    console.log(editClassTable)
    res.redirect('/admin/backstage.html')
});

// 社会责任 表名social
router.get('/getSocial',async function(req,res,next){
  //解决跨域问题
  res.set("Access-Control-Allow-Origin","*");
  let banner = await sql('select * from social')
  json.code = 1
  json.msg='成功'
  json.data=banner
  res.send(json)
})
//增加
router.post('/addSocial',upload.single('avatar'), function(req,res,next){
  res.set("Access-Control-Allow-Origin","*");
  console.log(req.file)
  console.log(req.body);
  const file = req.file
  // const extname = path.extname(file.originalname)
   const filepath = file.path
    // 获取上传成功之后的新文件路径
    const filename = file.destination + '\\' + file.originalname
  
  //重命名，借用fs的rename重命名的方法，第一参数是源文件地址路径，第二个参数是将源文件改名后的地址(和参数一地址相同，只不过名字变了而已，两个参数都是地址)
  fs.rename(filepath, filename,err=>{
    if(!err){
      var src = 'http://120.78.191.105/admin/images/' + file.originalname
    }
    // let {data} = req.body
    sql(`insert into social values(null,'${src}')`).then(data=>{
      res.redirect('/admin/backstage.html')
    })
  })
})
//修改
router.post('/editSocial',upload.single('avatar'),function(req,res,next){
  res.set("Access-Control-Allow-Origin","*");
  console.log(req.body)
  //获取图片的信息
  let file = req.file
  if(file !=undefined){
      const filepath = file.path
      const filename = file.destination+"\\"+ file.originalname
      fs.rename(filepath,filename, err =>{
          if(!err){
                  let src = 'http://120.78.191.105/admin/images/'+ file.originalname
                  let {id} = req.body
                  sql(`UPDATE social set src = '${src}', where id = ${id}`).then(data=>{
                  res.redirect('/admin/backstage.html')
              })
            }
          })
  }else{
          // res.redirect('/admin/backstage.html')
          console.log(err);
  }
})
//删除
router.post('/delSocial',async function(req, res, next) {
  res.set("Access-Control-Allow-Origin","*");
  let {id} = req.body
    id = Number(id)
    let editClassTable = await sql(`delete from social where id = ${id}`)
    console.log(editClassTable)
    res.redirect('/admin/backstage.html')
});

// 招标公告 表 bidding
router.get('/getBidding',async function(req,res,next){
  //解决跨域问题
  res.set("Access-Control-Allow-Origin","*");
  let banner = await sql('select * from bidding')
  json.code = 1
  json.msg='成功'
  json.data=banner
  res.send(json)
})
//增加
router.post('/addBidding',upload.single('avatar'), function(req,res,next){
  res.set("Access-Control-Allow-Origin","*");
  console.log(req.file)
  console.log(req.body);
  const file = req.file
  // const extname = path.extname(file.originalname)
   const filepath = file.path
    // 获取上传成功之后的新文件路径
    const filename = file.destination + '\\' + file.originalname
  
  //重命名，借用fs的rename重命名的方法，第一参数是源文件地址路径，第二个参数是将源文件改名后的地址(和参数一地址相同，只不过名字变了而已，两个参数都是地址)
  fs.rename(filepath, filename,err=>{
    if(!err){
      var src = 'http://120.78.191.105/admin/images/' + file.originalname
    }
    // let {data} = req.body
    sql(`insert into bidding values(null,'${src}')`).then(data=>{
      res.redirect('/admin/backstage.html')
    })
  })
})
//修改
router.post('/editBidding',upload.single('avatar'),function(req,res,next){
  res.set("Access-Control-Allow-Origin","*");
  console.log(req.body)
  //获取图片的信息
  let file = req.file
  if(file !=undefined){
      const filepath = file.path
      const filename = file.destination+"\\"+ file.originalname
      fs.rename(filepath,filename, err =>{
          if(!err){
                  let src = 'http://120.78.191.105/admin/images/'+ file.originalname
                  let {id} = req.body
                  sql(`UPDATE bidding set src = '${src}', where id = ${id}`).then(data=>{
                  res.redirect('/admin/backstage.html')
              })
            }
          })
  }else{
          // res.redirect('/admin/backstage.html')
          console.log(err);
  }
})
//删除
router.post('/delBidding',async function(req, res, next) {
  res.set("Access-Control-Allow-Origin","*");
  let {id} = req.body
    id = Number(id)
    let editClassTable = await sql(`delete from bidding where id = ${id}`)
    console.log(editClassTable)
    res.redirect('/admin/backstage.html')
});

// 分页
function fun(a,b) {
  router.post(a, async function (req, res, next) {
    res.set("Access-Control-Allow-Origin", "*");
    let { page } = req.body
    var banner = await sql(b)
    // 从小到大 排序
    banner.sort(function(c,d){
      return c.id-d.id
    })
    let a = Math.ceil(banner.length / 10 - 1)
    if (page == a) {     
      let b = banner.length - (a * 10)
      console.log(b);
      // console.log(page * 10);
      banner = banner.splice(page * 10, b)
      console.log(banner);
      res.send(banner)
    } else {
      banner = banner.splice(page * 10, 10)
      res.send(banner)
    }
  });
}
// 社会分页
fun('/fySociety','select * from social')
// 发展分页
fun('/fyDevelop','select * from develop')
// 企业荣誉
fun('/fyHonor','select * from honor')
// 企业新闻 媒体查询
fun('/fyNews','select * from news ')
//奶粉 鲜奶 液态奶 其他
fun('/fyPowder','select * from milk')







// fun('/fyNews','select * from news ')
// // 媒体关注
// fun('/fyMedia','select * from news')

// 酸奶yogurt
// fun('/fyMedia','select * from milk where table=1')
// // 奶粉 powder
// fun('/fyPowder','select * from milk where table=2')
// //鲜奶Fresh
// fun('/fyFresh','select * from milk where table=3')
// //液态奶 Liquid
// fun('/fyLiquid','select * from milk where table=4')
// // 其他 other
// fun('/fyOther','select * from milk where table=5')


/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express' });
});

module.exports = router;